

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="叶飞">
  <meta name="keywords" content="">
  
    <meta name="description" content="转载：http:&#x2F;&#x2F;mp.weixin.qq.com&#x2F;s?__biz&#x3D;MzI1MjkxNDU4OQ&#x3D;&#x3D;&amp;mid&#x3D;2247485214&amp;idx&#x3D;1&amp;sn&#x3D;847f0376a13e919363ed87786249733d&amp;chksm&#x3D;e9dd39ecdeaab0faeb7e0b9c6659c4760c3b059a56e072eb3bb71f00d46b924a35f1">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang-Channel">
<meta property="og:url" content="http://example.com/2022/04/27/20220427-Golang-Channel/index.html">
<meta property="og:site_name" content="博客">
<meta property="og:description" content="转载：http:&#x2F;&#x2F;mp.weixin.qq.com&#x2F;s?__biz&#x3D;MzI1MjkxNDU4OQ&#x3D;&#x3D;&amp;mid&#x3D;2247485214&amp;idx&#x3D;1&amp;sn&#x3D;847f0376a13e919363ed87786249733d&amp;chksm&#x3D;e9dd39ecdeaab0faeb7e0b9c6659c4760c3b059a56e072eb3bb71f00d46b924a35f1">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/20220427-Golang-Channel.assets/640.png">
<meta property="article:published_time" content="2022-04-27T08:03:28.000Z">
<meta property="article:modified_time" content="2022-04-27T08:33:52.259Z">
<meta property="article:author" content="叶飞">
<meta property="article:tag" content="channel">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/img/20220427-Golang-Channel.assets/640.png">
  
  
  
  <title>Golang-Channel - 博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>No Tomorrow</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Golang-Channel"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        叶飞
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-04-27 16:03" pubdate>
          星期三, 四月 27日 2022, 4:03 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          7.7k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          65 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Golang-Channel</h1>
            
            
              <div class="markdown-body">
                
                <blockquote>
<p>转载：<a target="_blank" rel="noopener" href="http://mp.weixin.qq.com/s?__biz=MzI1MjkxNDU4OQ==&amp;mid=2247485214&amp;idx=1&amp;sn=847f0376a13e919363ed87786249733d&amp;chksm=e9dd39ecdeaab0faeb7e0b9c6659c4760c3b059a56e072eb3bb71f00d46b924a35f1bbfd709e&amp;mpshare=1&amp;scene=24&amp;srcid=0426fHf7jTjgL7p11ivZywSc&amp;sharer_sharetime=1650983714479&amp;sharer_shareid=a3081d73eaefdd08617d03c46a7ecc14#rd">http://mp.weixin.qq.com/s?__biz=MzI1MjkxNDU4OQ==&amp;mid=2247485214&amp;idx=1&amp;sn=847f0376a13e919363ed87786249733d&amp;chksm=e9dd39ecdeaab0faeb7e0b9c6659c4760c3b059a56e072eb3bb71f00d46b924a35f1bbfd709e&amp;mpshare=1&amp;scene=24&amp;srcid=0426fHf7jTjgL7p11ivZywSc&amp;sharer_sharetime=1650983714479&amp;sharer_shareid=a3081d73eaefdd08617d03c46a7ecc14#rd</a></p>
<p>原作公众号：Go语言入门到精通</p>
</blockquote>
<h2 id="声明和定义channel"><a class="markdownIt-Anchor" href="#声明和定义channel"></a> 声明和定义channel</h2>
<hr>
<ul>
<li>
<p>Channel的本质是一个队列</p>
</li>
<li>
<ul>
<li><img src="/img/20220427-Golang-Channel.assets/640.png" srcset="/img/loading.gif" lazyload alt="图片"></li>
</ul>
</li>
<li>
<p>Channel是线程安全的, 也就是自带锁定功能</p>
</li>
<li>
<p>Channel声明和初始化</p>
</li>
<li>
<ul>
<li>声明: <code>var 变量名chan 数据类型</code></li>
<li>初始化: <code>mych := make(chan 数据类型, 容量)</code></li>
<li>Channel和切片还有字典一样, 必须make之后才能使用</li>
<li>Channel和切片还有字典一样, 是引用类型</li>
</ul>
</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 1.声明一个管道</span><br> <span class="hljs-keyword">var</span> mych <span class="hljs-keyword">chan</span> <span class="hljs-type">int</span><br> <span class="hljs-comment">// 2.初始化一个管道</span><br> mych = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">3</span>)<br> <span class="hljs-comment">// 3.查看管道的长度和容量</span><br> fmt.Println(<span class="hljs-string">&quot;长度是&quot;</span>, <span class="hljs-built_in">len</span>(mych), <span class="hljs-string">&quot;容量是&quot;</span>, <span class="hljs-built_in">cap</span>(mych))<br> <span class="hljs-comment">// 4.像管道中写入数据</span><br> mych&lt;- <span class="hljs-number">666</span><br> fmt.Println(<span class="hljs-string">&quot;长度是&quot;</span>, <span class="hljs-built_in">len</span>(mych), <span class="hljs-string">&quot;容量是&quot;</span>, <span class="hljs-built_in">cap</span>(mych))<br> <span class="hljs-comment">// 5.取出管道中写入的数据</span><br> num := &lt;-mych<br> fmt.Println(<span class="hljs-string">&quot;num = &quot;</span>, num)<br> fmt.Println(<span class="hljs-string">&quot;长度是&quot;</span>, <span class="hljs-built_in">len</span>(mych), <span class="hljs-string">&quot;容量是&quot;</span>, <span class="hljs-built_in">cap</span>(mych))<br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<ul>
<li>
<p>注意点:</p>
</li>
<li>
<ul>
<li>管道中只能存放声明的数据类型, 不能存放其它数据类型</li>
<li>管道中如果已经没有数据, 再取就会报错</li>
<li>如果管道中数据已满, 再写入就会报错</li>
</ul>
</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 1.声明一个管道</span><br> <span class="hljs-keyword">var</span> mych <span class="hljs-keyword">chan</span> <span class="hljs-type">int</span><br> <span class="hljs-comment">// 2.初始化一个管道</span><br> mych = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">3</span>)<br><br> <span class="hljs-comment">// 注意点: 管道中只能存放声明的数据类型, 不能存放其它数据类型</span><br> <span class="hljs-comment">//mych&lt;-3.14</span><br><br> <span class="hljs-comment">// 注意点: 管道中如果已经没有数据, </span><br> <span class="hljs-comment">// 并且检测不到有其它协程再往管道中写入数据, 那么再取就会报错</span><br> <span class="hljs-comment">//num = &lt;-mych</span><br> <span class="hljs-comment">//fmt.Println(&quot;num = &quot;, num)</span><br><br> <span class="hljs-comment">// 注意点: 如果管道中数据已满, 再写入就会报错</span><br> mych&lt;- <span class="hljs-number">666</span><br> mych&lt;- <span class="hljs-number">777</span><br> mych&lt;- <span class="hljs-number">888</span><br> mych&lt;- <span class="hljs-number">999</span><br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<ul>
<li>管道的关闭和遍历</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 1.创建一个管道</span><br> mych := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">3</span>)<br> <span class="hljs-comment">// 2.往管道中存入数据</span><br> mych&lt;<span class="hljs-number">-666</span><br> mych&lt;<span class="hljs-number">-777</span><br> mych&lt;<span class="hljs-number">-888</span><br> <span class="hljs-comment">// 3.遍历管道</span><br> <span class="hljs-comment">// 第一次遍历i等于0, len = 3,</span><br> <span class="hljs-comment">// 第二次遍历i等于1, len = 2</span><br> <span class="hljs-comment">// 第三次遍历i等于2, len = 1</span><br> <span class="hljs-comment">//for i:=0; i&lt;len(mych); i++&#123;</span><br> <span class="hljs-comment">// fmt.Println(&lt;-mych) // 输出结果不正确</span><br> <span class="hljs-comment">//&#125;</span><br><br> <span class="hljs-comment">// 3.写入完数据之后先关闭管道</span><br> <span class="hljs-comment">// 注意点: 管道关闭之后只能读不能写</span><br> <span class="hljs-built_in">close</span>(mych)<br> <span class="hljs-comment">//mych&lt;- 999 // 报错</span><br><br> <span class="hljs-comment">// 4.遍历管道</span><br> <span class="hljs-comment">// 利用for range遍历, 必须先关闭管道, 否则会报错</span><br> <span class="hljs-comment">//for value := range mych&#123;</span><br> <span class="hljs-comment">// fmt.Println(value)</span><br> <span class="hljs-comment">//&#125;</span><br><br> <span class="hljs-comment">// close主要用途:</span><br> <span class="hljs-comment">// 在企业开发中我们可能不确定管道有还没有有数据, 所以我们可能一直获取</span><br> <span class="hljs-comment">// 但是我们可以通过ok-idiom模式判断管道是否关闭, 如果关闭会返回false给ok</span><br> <span class="hljs-keyword">for</span>&#123;<br>  <span class="hljs-keyword">if</span> num, ok:= &lt;-mych; ok&#123;<br>   fmt.Println(num)<br>  &#125;<span class="hljs-keyword">else</span>&#123;<br>   <span class="hljs-keyword">break</span>;<br>  &#125;<br> &#125;<br> fmt.Println(<span class="hljs-string">&quot;数据读取完毕&quot;</span>)<br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<h2 id="channel阻塞现象"><a class="markdownIt-Anchor" href="#channel阻塞现象"></a> Channel阻塞现象</h2>
<ul>
<li>
<ul>
<li>单独在主线程中操作管道, 写满了会报错, 没有数据但读取取也会报错</li>
<li>只要在协程中操作管道过, 写满了就会阻塞, 没有数据去读取取也会阻塞</li>
</ul>
</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><span class="hljs-keyword">import</span> (<br> <span class="hljs-string">&quot;fmt&quot;</span><br> <span class="hljs-string">&quot;time&quot;</span><br>)<br><span class="hljs-comment">// 创建一个管道</span><br><span class="hljs-keyword">var</span> myCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">5</span>)<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">demo</span><span class="hljs-params">()</span></span>  &#123;<br> <span class="hljs-keyword">var</span> myCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">5</span>)<br> <span class="hljs-comment">//myCh&lt;-111</span><br> <span class="hljs-comment">//myCh&lt;-222</span><br> <span class="hljs-comment">//myCh&lt;-333</span><br> <span class="hljs-comment">//myCh&lt;-444</span><br> <span class="hljs-comment">//myCh&lt;-555</span><br> <span class="hljs-comment">//fmt.Println(&quot;我是第六次添加之前代码&quot;)</span><br> <span class="hljs-comment">//myCh&lt;-666</span><br> <span class="hljs-comment">//fmt.Println(&quot;我是第六次添加之后代码&quot;)</span><br><br> fmt.Println(<span class="hljs-string">&quot;我是第六次直接获取之前代码&quot;</span>)<br> &lt;-myCh<br> fmt.Println(<span class="hljs-string">&quot;我是第六次直接获取之后代码&quot;</span>)<br>&#125;<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">test</span><span class="hljs-params">()</span></span>  &#123;<br> <span class="hljs-comment">//myCh&lt;-111</span><br> <span class="hljs-comment">//myCh&lt;-222</span><br> <span class="hljs-comment">//myCh&lt;-333</span><br> <span class="hljs-comment">//myCh&lt;-444</span><br> <span class="hljs-comment">//myCh&lt;-555</span><br> <span class="hljs-comment">//fmt.Println(&quot;我是第六次添加之前代码&quot;)</span><br> <span class="hljs-comment">//myCh&lt;-666</span><br> <span class="hljs-comment">//fmt.Println(&quot;我是第六次添加之后代码&quot;)</span><br><br> <span class="hljs-comment">//fmt.Println(&quot;我是第六次直接获取之前代码&quot;)</span><br> <span class="hljs-comment">//&lt;-myCh</span><br> <span class="hljs-comment">//fmt.Println(&quot;我是第六次直接获取之后代码&quot;)</span><br>&#125;<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">example</span><span class="hljs-params">()</span></span>  &#123;<br> time.Sleep(time.Second * <span class="hljs-number">2</span>)<br> myCh&lt;<span class="hljs-number">-666</span><br>&#125;<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 1.同一个go程中操作管道</span><br> <span class="hljs-comment">// 写满了会报错</span><br> <span class="hljs-comment">//myCh&lt;-111</span><br> <span class="hljs-comment">//myCh&lt;-222</span><br> <span class="hljs-comment">//myCh&lt;-333</span><br> <span class="hljs-comment">//myCh&lt;-444</span><br> <span class="hljs-comment">//myCh&lt;-555</span><br> <span class="hljs-comment">//myCh&lt;-666</span><br><br> <span class="hljs-comment">// 没有了去取也会报错</span><br> <span class="hljs-comment">//&lt;-myCh</span><br><br> <span class="hljs-comment">// 2.在协程中操作管道</span><br> <span class="hljs-comment">// 写满了不会报错, 但是会阻塞</span><br> <span class="hljs-comment">//go test()</span><br><br> <span class="hljs-comment">// 没有了去取也不会报错, 也会阻塞</span><br> <span class="hljs-comment">//go test()</span><br><br> <span class="hljs-comment">//go demo()</span><br> <span class="hljs-comment">//go demo()</span><br> <br> <span class="hljs-comment">// 3.只要在协程中操作了管道, 就会发生阻塞现象</span><br> <span class="hljs-keyword">go</span> example()<br> fmt.Println(<span class="hljs-string">&quot;myCh之前代码&quot;</span>)<br> &lt;-myCh<br> fmt.Println(<span class="hljs-string">&quot;myCh之后代码&quot;</span>)<br><br> <span class="hljs-comment">//for&#123;</span><br> <span class="hljs-comment">// ;</span><br> <span class="hljs-comment">//&#125;</span><br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<h2 id="利用channel实现生产者消费者"><a class="markdownIt-Anchor" href="#利用channel实现生产者消费者"></a> 利用Channel实现生产者消费者</h2>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> (<br> <span class="hljs-string">&quot;fmt&quot;</span><br> <span class="hljs-string">&quot;math/rand&quot;</span><br> <span class="hljs-string">&quot;time&quot;</span><br>)<br><span class="hljs-comment">// 定义缓冲区</span><br><span class="hljs-keyword">var</span> myCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">5</span>)<br><span class="hljs-keyword">var</span> exitCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">bool</span>, <span class="hljs-number">1</span>)<br><br><span class="hljs-comment">// 定义生产者</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span></span>&#123;<br> rand.Seed(time.Now().UnixNano())<br> <span class="hljs-keyword">for</span> i:=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">10</span>;i++&#123;<br>  num := rand.Intn(<span class="hljs-number">100</span>)<br>  fmt.Println(<span class="hljs-string">&quot;生产者生产了: &quot;</span>, num)<br>  <span class="hljs-comment">// 往管道中写入数据</span><br>  myCh&lt;-num<br>  <span class="hljs-comment">//time.Sleep(time.Millisecond * 500)</span><br> &#125;<br> <span class="hljs-comment">// 生产完毕之后关闭管道</span><br> <span class="hljs-built_in">close</span>(myCh)<br> fmt.Println(<span class="hljs-string">&quot;生产者停止生产&quot;</span>)<br>&#125;<br><span class="hljs-comment">// 定义消费者</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span></span>  &#123;<br> <span class="hljs-comment">// 不断从管道中获取数据, 直到管道关闭位置</span><br> <span class="hljs-keyword">for</span>&#123;<br>  <span class="hljs-keyword">if</span> num, ok := &lt;-myCh; !ok&#123;<br>   <span class="hljs-keyword">break</span><br>  &#125;<span class="hljs-keyword">else</span>&#123;<br>   fmt.Println(<span class="hljs-string">&quot;---消费者消费了&quot;</span>, num)<br>  &#125;<br> &#125;<br> fmt.Println(<span class="hljs-string">&quot;消费者停止消费&quot;</span>)<br> exitCh&lt;-<span class="hljs-literal">true</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-keyword">go</span> producer()<br> <span class="hljs-keyword">go</span> consumer()<br> fmt.Println(<span class="hljs-string">&quot;exitCh之前代码&quot;</span>)<br> &lt;-exitCh<br> fmt.Println(<span class="hljs-string">&quot;exitCh之后代码&quot;</span>) <br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<h2 id><a class="markdownIt-Anchor" href="#"></a> </h2>
<h2 id="-2"><a class="markdownIt-Anchor" href="#-2"></a> </h2>
<h2 id="无缓冲channel和有缓存channel的区别"><a class="markdownIt-Anchor" href="#无缓冲channel和有缓存channel的区别"></a> 无缓冲Channel和有缓存Channel的区别</h2>
<blockquote>
<p>不带缓冲的channel是同步的。<br>
带缓冲的channel是异步的。</p>
</blockquote>
<ul>
<li><code>不带缓冲的channel</code>中，每一个发送者与接收者都会<code>阻塞当前线程</code>，只有当接受者与发送者都准备就绪了，channel才能正常使用。
<ul>
<li>所有在同一个线程中读取是不行的</li>
</ul>
</li>
<li>带缓冲的channel并不能无限的接收数据而不造成阻塞，能够接收的数据的个数取决于channel定义时，设定的缓冲的大小，只有在这个缓冲大小范围之内，channel的发送才不会造成阻塞。
<ul>
<li>阻塞与否，取决于缓冲区大小</li>
</ul>
</li>
</ul>
<h3 id="无缓冲channel"><a class="markdownIt-Anchor" href="#无缓冲channel"></a> 无缓冲Channel</h3>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span><br><span class="hljs-keyword">var</span> myCh1 = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">5</span>)<br><span class="hljs-keyword">var</span> myCh2 = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">0</span>)<br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 有缓冲管道</span><br> <span class="hljs-comment">// 只写入, 不读取不会报错</span><br> <span class="hljs-comment">//myCh1&lt;-1</span><br> <span class="hljs-comment">//myCh1&lt;-2</span><br> <span class="hljs-comment">//myCh1&lt;-3</span><br> <span class="hljs-comment">//myCh1&lt;-4</span><br> <span class="hljs-comment">//myCh1&lt;-5</span><br> <span class="hljs-comment">//fmt.Println(&quot;len =&quot;,len(myCh1), &quot;cap =&quot;, cap(myCh1))</span><br><br> <span class="hljs-comment">// 无缓冲管道</span><br> <span class="hljs-comment">// 只有两端同时准备好才不会报错</span><br> <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> &#123;<br>  fmt.Println(&lt;-myCh2)<br> &#125;()<br> <span class="hljs-comment">// 只写入, 不读取会报错</span><br> myCh2&lt;<span class="hljs-number">-1</span><br> <span class="hljs-comment">//fmt.Println(&quot;len =&quot;,len(myCh2), &quot;cap =&quot;, cap(myCh2))</span><br> <span class="hljs-comment">// 写入之后在同一个线程读取也会报错</span><br> <span class="hljs-comment">//fmt.Println(&lt;-myCh2)</span><br> <span class="hljs-comment">// 在主程中先写入, 在子程中后读取也会报错</span><br> <span class="hljs-comment">//go func() &#123;</span><br> <span class="hljs-comment">// fmt.Println(&lt;-myCh2)</span><br> <span class="hljs-comment">//&#125;()</span><br>&#125;<br></code></pre></td></tr></table></figure>
<hr>
<h3 id="无缓冲channel和有缓冲channel"><a class="markdownIt-Anchor" href="#无缓冲channel和有缓冲channel"></a> 无缓冲Channel和有缓冲Channel</h3>
<ul>
<li>
<ul>
<li>有缓冲管道具备异步的能力(写几个读一个或读几个)</li>
<li>无缓冲管道具备同步的能力(写一个读一个)</li>
</ul>
</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><span class="hljs-keyword">import</span> (<br> <span class="hljs-string">&quot;fmt&quot;</span><br> <span class="hljs-string">&quot;math/rand&quot;</span><br> <span class="hljs-string">&quot;time&quot;</span><br>)<br><span class="hljs-comment">// 定义缓冲区</span><br><span class="hljs-comment">//var myCh = make(chan int, 0)</span><br><span class="hljs-keyword">var</span> myCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>)<br><span class="hljs-keyword">var</span> exitCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">bool</span>, <span class="hljs-number">1</span>)<br><br><span class="hljs-comment">// 定义生产者</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">producer</span><span class="hljs-params">()</span></span>&#123;<br> rand.Seed(time.Now().UnixNano())<br> <span class="hljs-keyword">for</span> i:=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">10</span>;i++&#123;<br>  num := rand.Intn(<span class="hljs-number">100</span>)<br>  fmt.Println(<span class="hljs-string">&quot;生产者生产了: &quot;</span>, num)<br>  <span class="hljs-comment">// 往管道中写入数据</span><br>  myCh&lt;-num<br>  <span class="hljs-comment">//time.Sleep(time.Millisecond * 500)</span><br> &#125;<br> <span class="hljs-comment">// 生产完毕之后关闭管道</span><br> <span class="hljs-built_in">close</span>(myCh)<br> fmt.Println(<span class="hljs-string">&quot;生产者停止生产&quot;</span>)<br>&#125;<br><span class="hljs-comment">// 定义消费者</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">consumer</span><span class="hljs-params">()</span></span>  &#123;<br> <span class="hljs-comment">// 不断从管道中获取数据, 直到管道关闭位置</span><br> <span class="hljs-keyword">for</span>&#123;<br>  <span class="hljs-keyword">if</span> num, ok := &lt;-myCh; !ok&#123;<br>   <span class="hljs-keyword">break</span><br>  &#125;<span class="hljs-keyword">else</span>&#123;<br>   fmt.Println(<span class="hljs-string">&quot;---消费者消费了&quot;</span>, num)<br>  &#125;<br> &#125;<br> fmt.Println(<span class="hljs-string">&quot;消费者停止消费&quot;</span>)<br> exitCh&lt;-<span class="hljs-literal">true</span><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-keyword">go</span> producer()<br> <span class="hljs-keyword">go</span> consumer()<br> fmt.Println(<span class="hljs-string">&quot;exitCh之前代码&quot;</span>)<br> &lt;-exitCh<br> fmt.Println(<span class="hljs-string">&quot;exitCh之后代码&quot;</span>)<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>IO的延迟说明: 看到的输出结果和我们想象的不太一样, 是因为IO输出非常消耗性能, 输出之后还没来得及赋值可能就跑去执行别的协程了</p>
</blockquote>
<hr>
<h2 id="单向管道和双向管道"><a class="markdownIt-Anchor" href="#单向管道和双向管道"></a> 单向管道和双向管道</h2>
<ul>
<li>默认情况下所有管道都是双向了(可读可写)</li>
<li>但是在企业开发中, 我们经常需要用到将一个管道作为参数传递</li>
<li>在传递的过程中希望对方只能单向使用, 要么只能写,要么只能读</li>
</ul>
<h3 id="双向管道"><a class="markdownIt-Anchor" href="#双向管道"></a> 双向管道</h3>
<ul>
<li><code>var myCh chan int = make(chan int, 0)</code></li>
</ul>
<h3 id="单向管道"><a class="markdownIt-Anchor" href="#单向管道"></a> 单向管道</h3>
<ul>
<li>
<p><code>var myCh chan&lt;- int = make(chan&lt;- int, 0)</code></p>
<ul>
<li>只写：数据传入管道</li>
</ul>
</li>
<li>
<p><code>var myCh &lt;-chan int = make(&lt;-chan int, 0)</code></p>
<ul>
<li>只读：数据从管道出来</li>
</ul>
</li>
<li>
<ul>
<li></li>
</ul>
</li>
<li>
<p>注意点:</p>
</li>
<li>
<ul>
<li>双向管道可以自动转换为任意一种单向管道</li>
<li>单向管道不能转换为双向管道</li>
</ul>
</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><br><span class="hljs-keyword">import</span> <span class="hljs-string">&quot;fmt&quot;</span><br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 1.定义一个双向管道</span><br> <span class="hljs-keyword">var</span> myCh <span class="hljs-keyword">chan</span> <span class="hljs-type">int</span> = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">5</span>)<br><br> <span class="hljs-comment">// 2.将双向管道转换单向管道</span><br> <span class="hljs-keyword">var</span> myCh2 <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-type">int</span><br> myCh2 = myCh<br> fmt.Println(myCh2)<br> <span class="hljs-keyword">var</span> myCh3 &lt;-<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span><br> myCh3 = myCh<br> fmt.Println(myCh3)<br><br> <span class="hljs-comment">// 3.双向管道,可读可写</span><br> myCh&lt;<span class="hljs-number">-1</span><br> myCh&lt;<span class="hljs-number">-2</span><br> myCh&lt;<span class="hljs-number">-3</span><br> fmt.Println(&lt;-myCh)<br> <br> <span class="hljs-comment">// 3.只写管道,只能写, 不能读</span><br> <span class="hljs-comment">// myCh2&lt;-666</span><br> <span class="hljs-comment">// fmt.Println(&lt;-myCh2)</span><br><br> <span class="hljs-comment">// 4.指读管道, 只能读,不能写</span><br> fmt.Println(&lt;-myCh3)<br> <span class="hljs-comment">//myCh3&lt;-666</span><br> <br> <span class="hljs-comment">// 注意点: 管道之间赋值是地址传递, 以上三个管道底层指向相同容器</span><br>&#125;<br></code></pre></td></tr></table></figure>
<ul>
<li>单向管道作为函数参数</li>
</ul>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs go"><span class="hljs-keyword">package</span> main<br><span class="hljs-keyword">import</span> (<br> <span class="hljs-string">&quot;fmt&quot;</span><br> <span class="hljs-string">&quot;math/rand&quot;</span><br> <span class="hljs-string">&quot;time&quot;</span><br>)<br><span class="hljs-comment">// 定义生产者</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">producer</span><span class="hljs-params">(myCh <span class="hljs-keyword">chan</span>&lt;- <span class="hljs-type">int</span>)</span></span>&#123;<br> rand.Seed(time.Now().UnixNano())<br> <span class="hljs-keyword">for</span> i:=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">10</span>;i++&#123;<br>  num := rand.Intn(<span class="hljs-number">100</span>)<br>  fmt.Println(<span class="hljs-string">&quot;生产者生产了: &quot;</span>, num)<br>  <span class="hljs-comment">// 往管道中写入数据</span><br>  myCh&lt;-num<br>  <span class="hljs-comment">//time.Sleep(time.Millisecond * 500)</span><br> &#125;<br> <span class="hljs-comment">// 生产完毕之后关闭管道</span><br> <span class="hljs-built_in">close</span>(myCh)<br> fmt.Println(<span class="hljs-string">&quot;生产者停止生产&quot;</span>)<br>&#125;<br><span class="hljs-comment">// 定义消费者</span><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">consumer</span><span class="hljs-params">(myCh &lt;-<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>)</span></span>  &#123;<br> <span class="hljs-comment">// 不断从管道中获取数据, 直到管道关闭位置</span><br> <span class="hljs-keyword">for</span>&#123;<br>  <span class="hljs-keyword">if</span> num, ok := &lt;-myCh; !ok&#123;<br>   <span class="hljs-keyword">break</span><br>  &#125;<span class="hljs-keyword">else</span>&#123;<br>   fmt.Println(<span class="hljs-string">&quot;---消费者消费了&quot;</span>, num)<br>  &#125;<br> &#125;<br> fmt.Println(<span class="hljs-string">&quot;消费者停止消费&quot;</span>)<br><br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> &#123;<br> <span class="hljs-comment">// 定义缓冲区</span><br> <span class="hljs-keyword">var</span> myCh = <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-type">int</span>, <span class="hljs-number">5</span>)<br> <span class="hljs-keyword">go</span> producer(myCh)<br> consumer(myCh)<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>一个人走的太慢，一群人才能走的更远。</p>
</blockquote>
<h2 id="总结"><a class="markdownIt-Anchor" href="#总结"></a> 总结</h2>
<h3 id="1-channel的特性"><a class="markdownIt-Anchor" href="#1-channel的特性"></a> 1 Channel的特性</h3>
<p>Channel是异步进行的, channel存在3种状态：</p>
<ul>
<li>nil，未初始化的状态，只进行了声明，或者手动赋值为nil</li>
<li>active，正常的channel，可读或者可写</li>
<li>closed，已关闭，千万不要误认为关闭channel后，channel的值是nil</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:left">操作</th>
<th style="text-align:left">一个零值nil通道</th>
<th style="text-align:left">一个非零值但已关闭的通道</th>
<th style="text-align:left">一个非零值且尚未关闭的通道</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">关闭</td>
<td style="text-align:left">产生恐慌</td>
<td style="text-align:left">产生恐慌</td>
<td style="text-align:left">成功关闭</td>
</tr>
<tr>
<td style="text-align:left">发送数据</td>
<td style="text-align:left">永久阻塞</td>
<td style="text-align:left">产生恐慌</td>
<td style="text-align:left">阻塞或者成功发送</td>
</tr>
<tr>
<td style="text-align:left">接收数据</td>
<td style="text-align:left">永久阻塞</td>
<td style="text-align:left">永不阻塞</td>
<td style="text-align:left">阻塞或者成功接收</td>
</tr>
</tbody>
</table>
<h3 id="2-channel的同步和异步"><a class="markdownIt-Anchor" href="#2-channel的同步和异步"></a> 2 channel的同步和异步</h3>
<ul>
<li>同步会阻塞当前线程，知道数据被读取</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Golang/" class="category-chain-item">Golang</a>
  
  
    <span>></span>
    
  <a href="/categories/Golang/%E5%9F%BA%E7%A1%80/" class="category-chain-item">基础</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/channel/">#channel</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Golang-Channel</div>
      <div>http://example.com/2022/04/27/20220427-Golang-Channel/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>叶飞</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年4月27日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/04/27/20220427-Golang%E9%81%8D%E5%8E%86%E6%96%87%E4%BB%B6%E5%A4%B9/" title="Golang遍历文件夹">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Golang遍历文件夹</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/04/26/20220426-PowerShell%E5%9C%A8%E5%BD%93%E5%89%8D%E7%9B%AE%E5%BD%95%E6%89%93%E5%BC%80%E6%96%87%E4%BB%B6%E7%AE%A1%E7%90%86%E5%99%A8/" title="PowerShell在当前目录打开文件管理器">
                        <span class="hidden-mobile">PowerShell在当前目录打开文件管理器</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.1/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
